<template>
  <div class="Cart">
    <div class="header">
      <index-header 
        title="购物车" 
        title1="天鹿市场" 
        title2="天鹿的SuperStore" 
        titleBgColor='#ff5200' 
        placeholder="搜索天鹿商品关键词"
        ifTitleClick
        :searchEvent="handleSearch"
        >
        <template #other>
          <div class="other">
            <div class="totleMoney">
              已选商品:
              <span>¥ {{totleMoney}}</span>
            </div>
            <div class="toPay" :style="{background: totleMoney === 0?'#888888':null, padding: '15px 30px'}" @click="handleOrderDetail">
              结算
            </div>
          </div>
        </template>
      </index-header>
    </div>
    <div class="main">
      <div class="allSelect">
        <el-checkbox v-model="isAllSelect" @change="handleAllSelect">全选</el-checkbox>
      </div>
      <div class="cartsItem" v-for="(item,index) in myCart" :key="index">
        <div class="shopName">
          <el-checkbox v-model="item.shopSelect" @change="checked => handleShopSelect(checked,index)">
            <i class="iconfont icon-shop1170559easyiconnet" />店铺: {{item.title}}
          </el-checkbox>
        </div>
        <div class="content">
          <div :class="{'content-title': true, 'content-title-shopSelected': item.shopSelect}">
            <div class="item-name">商品名称</div>
            <div class="item-des">商品信息</div>
            <div class="item-price">金额</div>
            <div class="item-operate">操作</div>
          </div>
          <div class="content-main">
            <div :class="{
                'content-main-item': true, 
                'content-main-item-selected': good.selected,
                'content-main-item-lossActive': good.isLossActived,
              }" v-for="(good, i) in item.goods" :key="i">
              <div class="item-name">
                <span>
                  <el-checkbox v-model="good.selected" @change="checked => handleGoodSelect(checked,index)" />
                </span>
                <span>
                  <img :src="good.imgUrl" />
                </span>
                <span @click="handleDetail(good.id)">{{good.name}}</span>
              </div>
              <div class="item-des">
                <div class="des-contain">
                  <p v-for=" (value, keys) in good.info" :key="keys">
                    {{keys}}: {{value}}
                  </p>
                </div>
              </div>
              <div class="item-price">
                ¥ {{good.price}}
              </div>
              <div class="item-operate">
                <div class="operate-contain">
                  <el-popconfirm title="确定移入收藏夹吗？" @onConfirm="handleAddCollect(good.id, item.shopId)">
                    <p :style="{textAlign: 'center'}" slot="reference">移入收藏夹</p>
                  </el-popconfirm>
                  <el-popconfirm title="确定移出购物车吗？" @onConfirm="handleDelete(index,i,good.id)">
                    <p :style="{textAlign: 'center'}" slot="reference">删除</p>
                  </el-popconfirm>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="bottom">
      <div class="bottom-left">
        <div class="allSelect">
          <el-checkbox v-model="isAllSelect" @change="handleAllSelect">全选</el-checkbox>
        </div>
        <el-popconfirm title="确定全部移出购物车吗？" @onConfirm="handleDelete2">
          <p :style="{textAlign: 'center'}" slot="reference">删除</p>
        </el-popconfirm>
        <p @click="handleLossActived">清除失效</p>
        <el-popconfirm title="确定全部移到收藏夹吗？" @onConfirm="handleAddCollect(false)">
          <p :style="{textAlign: 'center'}" slot="reference">移入收藏夹</p>
        </el-popconfirm>
      </div>
      <div class="bottom-right">
        <p>已选商品<span>{{totleNum}}</span>件</p>
        <p>合计<span :style="{paddingRight: '30px'}">¥ {{totleMoney}}</span></p>
        <div class="toPay" :style="{background: totleMoney === 0?'#888888':null}" @click="handleOrderDetail">
          结算
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import IndexHeader from '@/components/IndexHeader'
import { mapState, mapActions } from 'vuex';
export default {
  name: '',
  components: {
    IndexHeader
  },
  computed: {
    ...mapState({
      myCart: state => state.cart.myCart,
      userInfo: state => state.user.userInfo,
      login: state => state.user.login
    }),
    totleMoney () {
      let money = 0;
      this.myCart.forEach(item => {
        item.goods.forEach(good => {
          if (good.selected) {
            money += good.price;
          }
        })
      });
      return money;
    },
    totleNum () {
      let num = 0;
      this.myCart.forEach(item => {
        item.goods.forEach(good => {
          if (good.selected) {
            num += 1;
          }
        })
      });
      return num;
    }
  },
  data () {
    return {
      isAllSelect: false,
      selectList: [],
    };
  },  
  created(){
    //做页面刷新判断
    this.fetchCartInfo({ user_id: this.login? this.userInfo.user_id : JSON.parse(localStorage.userInfo).user_id });
  },
  methods: {
    ...mapActions(['fetchCartInfo', 'fetchDeleteFromCart', 'fetchDeleteMore', 'fetchClearFailedGoods', 'fetchAddToCollect','fetchSearchGoods']),
    handleDetail (id) {
      this.$router.push({
        name: 'Detail',
        query: {
          goods_id: id
        }
      });
    },
    handleAllSelect (checked) {
      this.myCart.forEach(item => {
        item.shopSelect = checked;
        item.goods.forEach(good => {
          if (!good.isLossActived) {
            good.selected = checked;
          }
        })
      })
    },
    handleShopSelect (checked, whichShop) {
      const arr = [];
      this.myCart[whichShop].goods.forEach(good => {
        if (!good.isLossActived) {
          good.selected = checked;
        }
      });
      //监听一下 isAllSelect
      this.myCart.forEach(item => {
        arr.push(item.shopSelect);
      });
      this.isAllSelect = arr.reduce((a, b) => a && b);
    },
    handleGoodSelect (checked, whichShop) {
      //监听一下 shopSelect
      const arr = [];
      const arr2 = [];
      this.myCart[whichShop].goods.forEach(good => {
        if (good.isLossActived) {
          arr.push(true);
        } else {
          arr.push(good.selected);
        }
      });
      this.myCart[whichShop].shopSelect = arr.reduce((a, b) => a && b);
      //监听一下 isAllSelect
      this.myCart.forEach(item => {
        arr2.push(item.shopSelect);
      });
      this.isAllSelect = arr2.reduce((a, b) => a && b);
    },
    handleDelete (whichShop, whichGood, goods_id) {
      this.myCart[whichShop].goods.splice(whichGood, 1);
      if (this.myCart[whichShop].goods.length === 0) {
        this.myCart.splice(whichShop, 1);
      }
      this.fetchDeleteFromCart({ user_id: this.userInfo.user_id, goods_id });
    },
    handleDelete2 () {
      const goods_idList = [];
      this.myCart.forEach(item => {
        item.goods = item.goods.filter(good => { 
          if(good.selected){
            goods_idList.push(good.id);
          }
          return !good.selected;
        });
      });
      if(goods_idList.length === 0){
        this.$message({ type: 'warning', message: '勾选你想删除的宝贝。', showClose: true });
        return ;
      }
      this.myCart.forEach((item,index) => {
        if(item.goods.length === 0){
          this.myCart.splice(index,1)
        }
      })
      this.fetchDeleteMore({ user_id: this.userInfo.user_id, goods_idList });
    },
    handleLossActived () {
      const goods_idList = [];
      this.myCart.forEach((item,index) => {
        item.goods = item.goods.filter(good => {
          if(good.isLossActived){
            goods_idList.push(good.id);
          }
          return !good.isLossActived
        });
        if(item.goods.length === 0){
          this.myCart.splice(index,1);
        }
      });
      if(goods_idList.length === 0){
        this.$message({ type: 'warning', message: '购物车中没有失效的宝贝哦。', showClose: true });
        return ;
      }
      this.fetchClearFailedGoods({ user_id: this.userInfo.user_id, goods_idList });
    },
    handleOrderDetail () {
      //筛出已选的商品  和 对应有选择商品的那个店铺
      const orderGood = [];
      const orderShop = [];
      const orderShopArr = [];
      this.myCart.forEach(shop => {
        shop.goods.forEach(good => {
          if(good.selected){
            orderGood.push({...good, shopId: shop.shopId });
            if(!orderShopArr.includes(shop.shopId)){
              orderShopArr.push(shop.shopId);
              orderShop.push({
                shopName: shop.title,
                shopId: shop.shopId
              });
            }
          }
        })
      });
      if (this.totleMoney !== 0) {
        this.$store.commit('user/saveCartNum', -orderGood.length);
        this.$router.push({ 
          name: 'MyOrderDetail', 
          params: {
            whichPage: 'Cart', 
            orderDetail: {
              orderGood,
              orderShop
            }
          } 
        });
      } else {
        return false;
      }
    },
    handleAddCollect(id, shopId){
      const goods_idList = [];
      if(id){
        let deleteArr = null;
        this.myCart.forEach((shop,index) => {
          if(shop.shopId === shopId){
            shop.goods.forEach((good,i) => {
              if(good.id === id){
                this.myCart[index].goods.splice(i,1);
              }
            });
          }
          if(shop.goods.length === 0){
            deleteArr = shop.shopId;
          }
        });
        this.myCart.forEach((item,index) => {
          if(item.shopId === deleteArr){
            this.myCart.splice(index,1);
          }
        })
        this.fetchAddToCollect({ user_id: this.userInfo.user_id, goods_idList: [id] });
      }else{
        const shop_select = [];
        this.myCart.forEach(item => {
          item.goods.forEach((good,index) => {
           if(good.selected){
             goods_idList.push(good.id);
           }
          });
          if(item.shopSelect){
            shop_select.push(item.shopId);
          }
        });
        if(goods_idList.length === 0){
          this.$message({ type: 'warning', message: '勾选你想收藏的宝贝。', showClose: true });
          return ;
        }
        goods_idList.forEach(sGood => {
          this.myCart.forEach((shop,index) => {
            shop.goods.forEach((good,i) => {
              if(good.id === sGood){
                this.myCart[index].goods.splice(i,1);
              } 
            })
          })
        });
        shop_select.forEach(item => {
          this.myCart.forEach((shop,index) => {
            if(item === shop.shopId){
              this.myCart.splice(index,1);
            }
          })
        });
        this.fetchAddToCollect({ user_id: this.userInfo.user_id, goods_idList });
        
      }
    },
    handleSearch(content){
      console.log(content)
    }
  },
}
</script>
<style lang='scss' scoped src="./index.scss" />